package com.wjzjq.hiring.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;

import com.wjzjq.hiring.talent.entity.TalentEntity;

/**
 * 统计在线人数的监听器<br>
 * 监听session 和 服务器<br>
 * 2016年9月28日
 * 
 * @author gzy 无极之岚
 */
@WebListener
public class HttpSessionListener
		implements javax.servlet.http.HttpSessionListener, ServletContextListener, HttpSessionAttributeListener {
	private int count;
	public Map<String, HttpSession> loginMap = new HashMap();

	/**
	 * 统计在线人数
	 * 
	 * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
	 */
	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		count++;
		arg0.getSession().getServletContext().setAttribute("count", count);
		;
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		count--;
		arg0.getSession().getServletContext().setAttribute("count", count);
		;
	}

	/**
	 * 系统初始化
	 */
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * 单态登录
	 */

	@Override
	/**
	 * HttpSession.setAttribute()时会调用
	 * 
	 * @param arg0
	 */
	public void attributeAdded(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		String objName = arg0.getName();
		if ("talent".equals(objName)) {
			// 获取当前session的存储
			Object talentObj = arg0.getValue();
			HttpSession session = loginMap.get(talentObj);
			// 检查map里是否有此帐号,若有，则把此帐号的session失效
			if (session != null) {
				session.invalidate();
			}
			// 新账号关联
			loginMap.put(objName, arg0.getSession());

		}

	}

	@Override
	/**
	 * HttpSession.removeAttribute(),HttpSession.invalidate()时会调用
	 * 
	 * @param arg0
	 */
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		String objName = arg0.getName();
		if ("talent".equals(objName)) {
			// 获取当前session的存储
			Object talentObj = arg0.getValue();
			String code = ((TalentEntity) talentObj).getCode();
			String password = ((TalentEntity) talentObj).getPassword();
			// 检查map里是否有此帐号,若有，则把此帐号的session失效
			if (loginMap.get(talentObj) != null) {
				loginMap.remove(talentObj);
			}

		}
	}

	@Override
	/**
	 * HttpSession.setAttribute()时会调用
	 * 
	 * @param arg0
	 */
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub

	}

}
